package com.yhw.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhw.common.exception.Assert;
import com.yhw.common.result.ResponseEnum;
import com.yhw.srb.base.util.JwtUtils;
import com.yhw.srb.core.mapper.UserAccountMapper;
import com.yhw.srb.core.mapper.UserLoginRecordMapper;
import com.yhw.srb.core.pojo.entity.UserAccount;
import com.yhw.srb.core.pojo.entity.UserInfo;
import com.yhw.srb.core.mapper.UserInfoMapper;
import com.yhw.srb.core.pojo.entity.UserLoginRecord;
import com.yhw.srb.core.pojo.query.UserInfoQuery;
import com.yhw.srb.core.pojo.vo.LoginVO;
import com.yhw.srb.core.pojo.vo.RegisterVO;
import com.yhw.srb.core.pojo.vo.UserIndexVO;
import com.yhw.srb.core.pojo.vo.UserInfoVO;
import com.yhw.srb.core.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author yhw
 * @since 2022-08-29
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private UserLoginRecordMapper userLoginRecordMapper;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void register(RegisterVO registerVO) {

        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getMobile,registerVO.getMobile());
        Integer count = baseMapper.selectCount(queryWrapper);
        //MOBILE_EXIST_ERROR(-207, "手机号已被注册"),
        Assert.isTrue(count==0, ResponseEnum.MOBILE_EXIST_ERROR);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserType(registerVO.getUserType());
        userInfo.setMobile(registerVO.getMobile());
        userInfo.setNickName(registerVO.getMobile());
        userInfo.setName(registerVO.getMobile());
        String password = DigestUtils.md5Hex(registerVO.getPassword());  // 密码加密  md5Hex 这个要导入依赖 commons-codec
        userInfo.setPassword(password);
        userInfo.setStatus(UserInfo.STATUS_NORMAL);  // 状态 正常
        userInfo.setHeadImg(UserInfo.mrHeadImg);   // 默认头像

        baseMapper.insert(userInfo);

        //创建用户账户
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userInfo.getId());
        userAccountMapper.insert(userAccount);
    }

    @Override
    public UserInfoVO login(LoginVO loginVO, String ip) {

        String mobile = loginVO.getMobile();
        String password = loginVO.getPassword();
        Integer userType = loginVO.getUserType();

        // 根据手机号 查询 数据库 获取用户信息
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getMobile,mobile);
        queryWrapper.eq(UserInfo::getUserType, userType);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);

        // 用户不存在
        //LOGIN_MOBILE_ERROR(-208, "用户不存在"),
        Assert.notNull(userInfo,ResponseEnum.LOGIN_MOBILE_ERROR);

        // 校验密码
        //LOGIN_PASSWORD_ERROR(-209, "密码不正确")
        String jmpassword = DigestUtils.md5Hex(password);  // 注册的时候 是加密 存进去的
        Assert.equals(jmpassword,userInfo.getPassword(),ResponseEnum.LOGIN_PASSWORD_ERROR);

        // 用户是否被禁用
        //LOGIN_DISABLED_ERROR(-210, "用户已被禁用")
        Assert.equals(userInfo.getStatus(),UserInfo.STATUS_NORMAL,ResponseEnum.LOGIN_LOKED_ERROR);

        // 记录登录日志  数据库中有一个表是专门记录 登录的
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setUserId(userInfo.getId());
        userLoginRecord.setIp(ip);
        userLoginRecordMapper.insert(userLoginRecord);

        // 利用JWT工具类 生成token 返回给前端
        String token = JwtUtils.createToken(userInfo.getId(), userInfo.getName());
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(userInfo,userInfoVO);
        userInfoVO.setToken(token);

        return userInfoVO;
    }

    @Override
    public IPage<UserInfo> listPage(Page<UserInfo> pageParam, UserInfoQuery userInfoQuery) {

        if (userInfoQuery == null){
           return baseMapper.selectPage(pageParam, null);
        }

        String mobile = userInfoQuery.getMobile();
        Integer status = userInfoQuery.getStatus();
        Integer userType = userInfoQuery.getUserType();

        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!StringUtils.isBlank(mobile),UserInfo::getMobile,mobile)
                    .eq(status != null,UserInfo::getStatus,status)
                    .eq(userType != null,UserInfo::getUserType,userType);
                    // 为true 就生效

        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, queryWrapper);

        return userInfoPage;
    }

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);
        baseMapper.updateById(userInfo);
    }

    @Override
    public Boolean checkMobile(String mobile) {

        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getMobile,mobile);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }

    @Override
    public UserIndexVO getIndexUserInfo(Long userId) {

        //用户信息
        UserInfo userInfo = baseMapper.selectById(userId);

        //账户信息
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccount::getUserId, userId);
        UserAccount userAccount = userAccountMapper.selectOne(queryWrapper);

        //登录信息
        LambdaQueryWrapper<UserLoginRecord> loginQueryWrapper = new LambdaQueryWrapper<>();
        loginQueryWrapper
                .eq(UserLoginRecord::getUserId, userId)
                .orderByDesc(UserLoginRecord::getId)
                .last("limit 1");
        UserLoginRecord userLoginRecord = userLoginRecordMapper.selectOne(loginQueryWrapper);

        //组装结果数据
        UserIndexVO userIndexVO = new UserIndexVO();
        userIndexVO.setUserId(userInfo.getId());
        userIndexVO.setUserType(userInfo.getUserType());
        userIndexVO.setName(userInfo.getName());
        userIndexVO.setNickName(userInfo.getNickName());
        userIndexVO.setHeadImg(userInfo.getHeadImg());
        userIndexVO.setBindStatus(userInfo.getBindStatus());
        userIndexVO.setAmount(userAccount.getAmount());
        userIndexVO.setFreezeAmount(userAccount.getFreezeAmount());
        userIndexVO.setLastLoginTime(userLoginRecord.getCreateTime());

        return userIndexVO;
    }

    @Override
    public String getMobileByBindCode(String bindCode) {

        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getBindCode, bindCode);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        return userInfo.getMobile();

    }


}
